package com.abc.recycling.controller;

import com.abc.recycling.domain.SysConfig;
import com.abc.recycling.service.SysConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/config")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class SysConfigController {

    private final SysConfigService configService;
    
    /**
     * 配置列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<SysConfig> configs = configService.getAllConfigs();
        model.addAttribute("configs", configs);
        return "config/list";
    }
    
    /**
     * 创建配置页面
     */
    @GetMapping("/create")
    public String createForm() {
        return "config/edit";
    }
    
    /**
     * 编辑配置页面
     */
    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable Long id, Model model) {
        SysConfig config = configService.getConfig(id);
        model.addAttribute("config", config);
        return "config/edit";
    }
    
    /**
     * 创建配置
     */
    @PostMapping("/create")
    @ResponseBody
    public SysConfig create(@RequestBody SysConfig config) {
        return configService.createConfig(config);
    }
    
    /**
     * 更新配置
     */
    @PutMapping("/update")
    @ResponseBody
    public SysConfig update(@RequestBody SysConfig config) {
        return configService.updateConfig(config);
    }
    
    /**
     * 删除配置
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public boolean delete(@PathVariable Long id) {
        return configService.deleteConfig(id);
    }
    
    /**
     * 更新配置状态
     */
    @PutMapping("/{id}/status")
    @ResponseBody
    public boolean updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        return configService.updateConfigStatus(id, status);
    }
    
    /**
     * 搜索配置
     */
    @GetMapping("/search")
    @ResponseBody
    public List<SysConfig> search(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String configKey,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Integer status) {
        return configService.searchConfigs(name, configKey, type, status);
    }
    
    /**
     * 检查键名是否存在
     */
    @GetMapping("/check-key")
    @ResponseBody
    public boolean checkKey(
            @RequestParam String configKey,
            @RequestParam(required = false) Long excludeId) {
        return configService.isKeyExists(configKey, excludeId);
    }
} 